package com.topcheer.base.gatewaynacos.dynamic;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.nacos.api.NacosFactory;
import com.alibaba.nacos.api.PropertyKeyConst;
import com.alibaba.nacos.api.config.ConfigService;
import com.alibaba.nacos.api.config.listener.Listener;
import com.alibaba.nacos.api.exception.NacosException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.gateway.route.RouteDefinition;
import org.springframework.core.env.Environment;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import java.util.List;
import java.util.Properties;
import java.util.concurrent.Executor;

/**
 * @author xutao
 * @Package com.topcheer.base.gatewaynacos.dynamic
 * @Description: 获取nacos的配置文件 加载route信息
 * @date 2020/1/10 23:00
 */
@Component
@Slf4j
public class DynamicRouteServiceImplByNacos {

    @Autowired
    Environment environment;

    @Autowired
    private DynamicRouteServiceImpl dynamicRouteService;

    public DynamicRouteServiceImplByNacos() {
    }
    @PostConstruct
    void init(){
        dynamicRouteByNacosListener("gateway-route","DEFAULT_GROUP");
    }

    /**
     * 监听Nacos Server下发的动态路由配置
     * @param dataId
     * @param group
     */
    public void dynamicRouteByNacosListener (String dataId, String group){
        try {
            Properties properties = new Properties();
            properties.put(PropertyKeyConst.NAMESPACE, environment.getProperty("spring.cloud.nacos.discovery.namespace"));
            properties.put(PropertyKeyConst.SERVER_ADDR,environment.getProperty("spring.cloud.nacos.discovery.server-addr") );
            ConfigService configService= NacosFactory.createConfigService(properties);
            String content = configService.getConfig(dataId, group, 5000);
            configService.addListener(dataId, group, new Listener()  {
                @Override
                public void receiveConfigInfo(String configInfo) {
                    read(configInfo,true);
                }
                @Override
                public Executor getExecutor() {
                    return null;
                }
            });
            read(content,false);
        } catch (NacosException e) {
            log.error("nacos dynamic route init error |",e);
        }
    }

    private void read(String configInfo,boolean update) {
        List<RouteDefinition> list = JSONObject.parseArray(configInfo,RouteDefinition.class);
        for(RouteDefinition definition:list){
            if(update){
                dynamicRouteService.update(definition);
            }else{
                dynamicRouteService.add(definition);
            }
        }
    }
}
